<template>
  <el-container>
    <el-aside width="250px">
      <hostsGroupTable function_choice="query" @childClick="envClick" />
    </el-aside>
    <el-container>
      <el-header style="font-size: 12px; width: 100%">
        <el-button type="primary" size="mini" @click="deploy_soft"
          >安装</el-button
        >
        <el-button type="primary" size="mini" disabled>配置调整</el-button>
        <el-button type="primary" size="mini" @click="open_log_dialog"
          >日志查看</el-button
        >
        <el-button type="primary" size="mini">重启</el-button>
        <el-button type="primary" size="mini" disabled>停止</el-button>
        <el-button type="primary" size="mini" disabled>销毁</el-button>
        <el-button type="primary" size="mini" disabled>刷新</el-button>

        <el-button-group style="margin-top: -1px">
          <el-button
            type="success"
            size="mini"
            style="margin-left: 5px"
            disabled
            >信息<i class="el-icon-video-camera-solid el-icon--right"></i
          ></el-button>
          <el-button type="primary" size="mini" @click="start_collection"
            >收集</el-button
          >
          <el-button type="primary" size="mini" @click="stop_collection"
            >停止</el-button
          >
        </el-button-group>
        <el-button-group style="margin-left: 5px">
          <SysCodeInput
            size="mini"
            sys_code_type="soft_subsumption_type"
            @childClick="select_check_CodoClick"
            :sys_code_value="select_dict.soft_subsumption_code"
          />
        </el-button-group>
      </el-header>
      <el-main>
        <el-table
          @selection-change="soft_table_selection_change"
          @current-change="check_soft"
          @cell-dblclick="tableDbclick"
          highlight-current-row
          cell-style="padding:0"
          :data="soft_table"
          style="font-size: 10px; width: 100%"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="软件名称"
            prop="soft_nick"
          >
          </el-table-column>
          <el-table-column prop="deploy_package_versions" label="版本">
            <template #default="{ row }">
              <el-row>
                <el-input
                  @blur="blurDeployPackageversions(row)"
                  v-if="row.input_on"
                  ref="deploy_package_versions_ref"
                  v-model="deploy_package_versions_swap"
                  style="width: 100%; height: 100%"
                  size="mini"
                ></el-input>
                <span v-else>{{ row.deploy_package_versions }}</span>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="软件类型" prop="soft_name"> </el-table-column>
          <el-table-column label="服务器名称" prop="host_nick">
          </el-table-column>
          <el-table-column label="设备IP" prop="host_ip"> </el-table-column>
          <el-table-column label="部署方式" prop="soft_install_name">
          </el-table-column>
          <el-table-column label="状态">
            <template v-slot="scope">
              <el-icon
                size="12"
                v-if="scope.row.deploy_event_status === '0'"
                style="color: #f56c6c"
                ><lightning
              /></el-icon>
              <el-icon
                size="12"
                v-if="scope.row.deploy_event_status === '1'"
                style="color: #67c23a"
                ><sunrise
              /></el-icon>
              <el-icon
                size="12"
                v-if="scope.row.deploy_event_status === '2'"
                style="color: #e6a23c"
                ><mostly-cloudy
              /></el-icon>
              <el-icon
                size="12"
                v-if="scope.row.deploy_event_status === '-1'"
                style="color: #909399"
                ><moon-night
              /></el-icon>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="信息"
            prop="deploy_event_info"
          >
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </el-container>
  <LogManage
    @childClick="close_open_log_dialog_value"
    :in_value="open_log_dialog_value"
    :soft_id="check_soft_id"
    :props_title_name="check_soft_nick"
  />
</template>

<script>
import hostsGroupTable from "@/components/communal/hosts_group_table.vue";
import LogManage from "@/components/communal/log_manage.vue";
import * as Request from "@/general/request";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { server_config } from "@/service_config";
import SysCodeInput from "@/components/communal/sys_code_input.vue";

export default {
  name: "resource_management",
  components: {
    hostsGroupTable,
    SysCodeInput,
    LogManage,
  },
  setup() {
    let soft_table = ref([]);
    let env_id = ref("");
    let selection_list = ref([]);
    let selection_soft_ids = ref([]);
    let table_soft_ids = ref([]);
    let websock = ref(null);
    let info_info_type = ref("");
    let info_info_text = ref("");
    let socket_reconnection_value = ref(0);
    let websocketsend_cron = ref(null);
    let select_dict = ref({});
    let check_soft_id = ref("");
    let check_soft_nick = ref("");
    const deploy_package_versions_ref = ref(null);
    let open_log_dialog_value = ref(false);
    let deploy_package_versions_swap = ref("");

    const tableDbclick = (row) => {
      row.input_on = !row.input_on;
      deploy_package_versions_swap.value = row.deploy_package_versions;
      setTimeout(() => {
        deploy_package_versions_ref.value.focus();
      }, 20);
    };

    const blurDeployPackageversions = (row) => {
      row.input_on = false;
      row.deploy_package_versions = deploy_package_versions_swap.value;
      put_update_app_version(row.soft_id, row.deploy_package_versions);
    };

    const select_check_CodoClick = (e) => {
      select_dict.value.soft_subsumption_code = e;
    };

    const envClick = (e) => {
      env_id.value = e;
      websock.value.close();
      get_env_host_app();
      clearInterval(websocketsend_cron.value);
      setTimeout(() => {
        start_collection();
      }, 200);
    };

    const open_log_dialog = () => {
      if (!check_soft_id.value) {
        ElMessage.warning("请选择一个软件");
        return;
      }
      open_log_dialog_value.value = true;
    };

    const check_soft = (row) => {
      if (row) {
        check_soft_id.value = row.soft_id;
        check_soft_nick.value = row.soft_nick + "日志管理";
      } else {
        check_soft_id.value = "";
      }
    };

    const close_open_log_dialog_value = () => {
      open_log_dialog_value.value = false;
    };

    const soft_table_selection_change = (e) => {
      selection_list.value = e;

      selection_soft_ids.value = [];
      let i = 0,
        len = e.length;
      for (; i < len; ) {
        selection_soft_ids.value.push(e[i].soft_id);
        i++;
      }
    };

    const start_collection = async () => {
      socket_reconnection_value.value = 0;
      await initWebSocket();
      ElMessage.success("正在获取最新信息..");
    };
    onMounted(start_collection);

    const stop_collection = () => {
      end_llection();
    };

    const end_llection = (warning_info) => {
      websock.value.close();
      info_info_type.value = "warning";
      info_info_text.value = "收集停止";
      websocketclose();
      if (!warning_info) {
        ElMessage.warning("已停止获取最新信息！");
      } else {
        ElMessage.warning(warning_info);
      }
    };

    const initWebSocket = () => {
      const wsuri = server_config["background_ws"] + "/soft_deploy_info";
      websock.value = new WebSocket(wsuri);
      websock.value.onmessage = websocketonmessage;
      websock.value.onopen = websocketonopen;
      websock.value.onerror = websocketonerror;
      websock.value.onclose = websocketclose;
    };

    const websocketonopen = () => {
      // 连接建立之后执行send方法发送数据
      websocketsend_cron.value = setInterval(() => {
        websocketsend(JSON.stringify(table_soft_ids.value));
      }, 5000);
      // websocketsend(JSON.stringify(table_soft_ids.value))
    };

    const websocketonerror = () => {
      // 连接建立失败重连
      if (socket_reconnection_value.value > 3) {
        return;
      }
      initWebSocket();
      socket_reconnection_value.value = socket_reconnection_value.value + 1;
    };

    const websocketonmessage = (e) => {
      // 数据接收
      const datas = JSON.parse(e.data);
      if (datas.success) {
        // this.$message.success(data.msg)
        info_info_type.value = "success";
        info_info_text.value = "正在收集";
        // datassetOption(data.data)
        let i = 0,
          len = soft_table.value.length;
        for (; i < len; ) {
          let a = 0,
            alen = datas.data.length;
          for (; a < alen; ) {
            if (soft_table.value[i]["soft_id"] === datas.data[a]["soft_id"]) {
              soft_table.value[i]["deploy_event_info"] =
                "[" +
                datas.data[a]["deploy_event_finish_time"] +
                "]" +
                datas.data[a]["deploy_event_info"];
              soft_table.value[i]["deploy_event_status"] =
                datas.data[a]["deploy_event_status"];
            }
            a++;
          }
          i++;
        }
      } else {
        // ElMessage.error(data.msg)
        info_info_type.value = "error";
        info_info_text.value = "收集失败";
        end_llection();
      }
    };

    const websocketsend = (Data) => {
      // 数据发送
      if (Data) {
        websock.value.send(Data);
      } else {
        websock.value.close();
      }
    };

    const websocketclose = () => {
      {
        // 关闭
        // console.log('断开连接', e)
        clearInterval(websocketsend_cron.value);
      }
    };

    const get_env_host_app = async () => {
      const response = await Request.GET(
        "/background/home/deploy/env_deploy_soft",
        { env_id: env_id.value }
      );
      if (response && response.data) {
        var return_data = response.data;
        if (return_data.success) {
          soft_table.value = return_data.data;
          table_soft_ids.value = [];
          let i = 0,
            len = soft_table.value.length;
          for (; i < len; ) {
            table_soft_ids.value.push(soft_table.value[i]["soft_id"]);
            i++;
          }

          ElMessage.success(return_data.msg);
        } else {
          ElMessage.error(return_data.msg);
        }
      }
    };

    const deploy_soft = async () => {
      if (!selection_soft_ids.value) {
        ElMessage.warning("请勾选一个软件");
        return;
      }

      const response = await Request.POST(
        "/background/home/deploy/deploy_soft/",
        { soft_ids: selection_soft_ids.value }
      );
      if (response && response.data) {
        var return_data = response.data;
        if (return_data.success) {
          // soft_table.value = return_data.data
          ElMessage.success(return_data.msg);
        } else {
          ElMessage.error(return_data.msg);
        }
      }
    };

    const put_update_app_version = async (soft_id, deploy_package_versions) => {
      const response = await Request.PUT(
        "/background/home/deploy/update_soft_version",
        {
          soft_id: soft_id,
          deploy_package_versions: deploy_package_versions,
        }
      );
      if (response && response.data) {
        var return_data = response.data;
        if (return_data.success) {
          // app_table.value = return_data.data
          ElMessage.success(return_data.msg);
        } else {
          ElMessage.error(return_data.msg);
        }
      }
    };

    return {
      envClick,
      soft_table,
      deploy_soft,
      soft_table_selection_change,
      selection_soft_ids,
      end_llection,
      start_collection,
      stop_collection,
      select_check_CodoClick,
      select_dict,
      deploy_package_versions_ref,
      tableDbclick,
      blurDeployPackageversions,
      deploy_package_versions_swap,
      check_soft,
      check_soft_id,
      check_soft_nick,
      close_open_log_dialog_value,
      open_log_dialog,
      open_log_dialog_value,
    };
  },
};
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
